package com.bugbuff.dubbo.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bugbuff.common.enums.SexEnum;
import com.bugbuff.common.mapper.*;
import com.bugbuff.common.pojo.*;
import com.bugbuff.common.service.PicUploadService;
import com.bugbuff.common.utils.UserThreadLocal;
import com.bugbuff.common.vo.ErrorResult;
import com.bugbuff.common.vo.PicUploadResult;
import com.bugbuff.dubbo.server.api.UserLikeApi;
import com.bugbuff.dubbo.server.api.VisitorsApi;
import com.bugbuff.dubbo.server.pojo.UserLike;
import com.bugbuff.dubbo.server.pojo.Visitors;
import com.bugbuff.dubbo.server.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class MyCenterService {
     @Autowired
     private UserMapper userMapper;
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private FaceEngineService faceEngineService;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RecommendUserService recommendUserService;

    @Reference
    private UserLikeApi userLikeApi;

    @Autowired
    private SmsService smsService;

    @Autowired
    private UserService userService;

    @Autowired
    private BlackListMapper blackListMapper;

    @Autowired
    private UserSettingsMapper userSettingsMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private TanHuaService tanHuaService;
    @Autowired
    private IMService imService;
    @Reference
    private VisitorsApi visitorsApi;

    public UserInfoVo queryUserInfoByUserId(Long userId) {
        if (ObjectUtil.isEmpty(userId)) {
            //如果查询id为null，就表示查询当前用户信息
            userId = UserThreadLocal.get().getId();
        }
        //查询用户信息
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(userId);
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }

        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class, "marriage");
        userInfoVo.setGender(userInfo.getSex().getValue() == 1 ? "man" : "women");
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
        return userInfoVo;
    }


    /**
     * 上传用户头像
     * @param file
     * @return
     */
    public Boolean saveHeadPhoto(MultipartFile file) {
        //获取当前登录用户
        User user = UserThreadLocal.get();
        try {
            //校验图片是否是人像，如果不是人像就返回false
            boolean b = this.faceEngineService.checkIsPortrait(file.getBytes());
            if (!b) {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        //图片上传到阿里云OSS
        PicUploadResult result = this.picUploadService.upload(file);
        if (StringUtils.isEmpty(result.getName())) {
            //上传失败
            return false;
        }

        //把头像更新到用户信息表中
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(result.getName());

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());

        return this.userInfoMapper.update(userInfo, queryWrapper) == 1;
    }

    /**
     * 更改用户信息
     * @param userInfoVo
     * @return
     */
    public Boolean saveUserInfoData(UserInfoVo userInfoVo) {
        User user = UserThreadLocal.get();
        UserInfo userInfo=new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setNickName(userInfoVo.getNickname());
        userInfo.setAge(DateUtil.ageOfNow(userInfoVo.getBirthday()));
        userInfo.setBirthday(userInfoVo.getBirthday());
        userInfo.setCity(userInfoVo.getCity());
        userInfo.setEdu(userInfoVo.getEducation());
        userInfo.setIndustry(userInfoVo.getProfession());
        userInfo.setSex(StringUtils.equalsIgnoreCase(userInfoVo.getGender(),"man")? SexEnum.MAN:SexEnum.WOMAN);
        userInfo.setIncome(StringUtils.replaceAll(userInfoVo.getIncome(),"k",""));
        userInfo.setMarriage(userInfoVo.getMarriage()==1?"已婚":"未婚");
        return userInfoService.updateUserInfoByUserId(userInfo);
    }


    /**
     * 查询互相喜欢总数、喜欢总数、粉丝总数
     * @return
     */
    public CountVo queryCounts() {
        //获取当前登录用户信息
        User user = UserThreadLocal.get();
        //封装CountVo对象
        CountVo countVo=new CountVo();
        countVo.setEachLoveCount(this.getMutualLike(user.getId()).size());
        countVo.setLoveCount(userLikeApi.queryLikeList(user.getId()).size());
        countVo.setFanCount(this.queryFansCount(user.getId()));
        return countVo;
    }

    /**
     * 查询粉丝数量
     * @param userId
     * @return
     */
    private Integer queryFansCount(Long userId) {
        List<UserLike> fans=userLikeApi.queryFansList(userId);
        if(CollUtil.isEmpty(fans)){
            return 0;
        }
        return fans.size();
    }

    /**
     * 查询相互喜欢的集合
     * @param userId
     * @return
     */
    private List<UserLike> getMutualLike(Long userId) {
        //查询我喜欢的用户的id集合
        List<Long> likeList = userLikeApi.queryLikeList(userId);
        //查询likeList集合中喜欢我的用户
        List<UserLike> mutualLikeList=userLikeApi.queryMutualLikeList(likeList,userId);
        if(CollUtil.isEmpty(mutualLikeList)){
            return ListUtil.empty();
        }
        return mutualLikeList;
    }

    /**
     * 根据类型查询喜欢列表
     * @param type
     * @param page
     * @param pagesize
     * @param nickname
     * @return
     */
    public PageResult queryLikeListByType(String type, Integer page, Integer pagesize, String nickname) {
        //获取当前登录用户
        User user = UserThreadLocal.get();
        PageResult pageResult=new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        List<UserLike> userLikeList=new ArrayList<>();
        List<Object> userIds=new ArrayList<>();
        switch (type){
            case "1":
                //相互关注
                userLikeList=this.getMutualLike(user.getId());
                userIds=CollUtil.getFieldValues(userLikeList,"userId");
                break;
            case "2":
                //我关注
                userIds.addAll(userLikeApi.queryLikeList(user.getId()));
                break;
            case "3":
                //粉丝
                userLikeList=userLikeApi.queryFansList(user.getId());
                userIds=CollUtil.getFieldValues(userLikeList,"userId");
                break;
                //访客
            case "4":
                List<Visitors> visitors = visitorsApi.topVisitor(user.getId(), page, pagesize);
                userIds=CollUtil.getFieldValues(visitors,"visitorUserId");
                break;

            default:
                return pageResult;
        }
        if(CollUtil.isEmpty(userIds)){
            return pageResult;
        }
        //模糊查询
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.in("user_id",userIds);
        if(StringUtils.isNotEmpty(nickname)){
            queryWrapper.like("nick_name",nickname);
        }
        List<UserInfo> userInfoList=userInfoService.queryUserInfoListByPage(queryWrapper,page,pagesize);
        List<UserLikeListVo> userLikeListVos=new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            UserLikeListVo userLikeListVo = new UserLikeListVo();
            userLikeListVo.setAge(userInfo.getAge());
            userLikeListVo.setAvatar(userInfo.getLogo());
            userLikeListVo.setCity(userInfo.getCity());
            userLikeListVo.setEducation(userInfo.getEdu());
            userLikeListVo.setGender(userInfo.getSex().name().toLowerCase());
            userLikeListVo.setId(userInfo.getUserId());
            userLikeListVo.setMarriage(StringUtils.equals(userInfo.getMarriage(), "已婚") ? 1 : 0);
            userLikeListVo.setNickname(userInfo.getNickName());
            //是否喜欢  userLikeApi中的isLike开放出来
            userLikeListVo.setAlreadyLove(this.userLikeApi.queryIsLike(user.getId(), userInfo.getUserId()));
            Double score = this.recommendUserService.queryScore(user.getId(), userInfo.getUserId());
            userLikeListVo.setMatchRate(Convert.toInt(score));
            userLikeListVos.add(userLikeListVo);
        }
        pageResult.setItems(userLikeListVos);
        return pageResult;
    }

    /**
     * 发送验证码
     * @return
     */
    public Boolean sendVerificationCode() {
        //获取登录用户id
        User user = UserThreadLocal.get();
        //获取手机号
        String mobile = user.getMobile();
        //发送短信验证码
        ErrorResult errorResult = smsService.sendCheckCode(mobile);
        if(errorResult==null){
            //发送成功
            return true;
        }
        return false;
    }

    /**
     * 校验验证码
     * @param checkCode
     * @return
     */
    public Boolean checkVerificationCode(String checkCode) {
        //获取登录用户信息
        User user = UserThreadLocal.get();
        //获取手机号
        String mobile = user.getMobile();
        Boolean result=userService.checkVerificationCode(mobile,checkCode);
        return result;
    }

    /**
     * 修改手机号
     * @param phone
     * @return
     */
    public ErrorResult updatePhone(String phone) {
        //获取登录用户信息
        User user = UserThreadLocal.get();
        return userService.updatePhoneByUserId(user.getId(),phone);
    }

    public UserSettingsVo queryUserSeetings() {
        User user = UserThreadLocal.get();
        QueryWrapper<Settings> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        Settings settings = userSettingsMapper.selectOne(queryWrapper);
        String question = tanHuaService.queryQuestion(user.getId());
        UserSettingsVo userSettingsVo = new UserSettingsVo();
        userSettingsVo.setId(user.getId().intValue());
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id", user.getId());
        String mobile = this.userMapper.selectOne(queryWrapper1).getMobile();
        userSettingsVo.setPhone(mobile);
        userSettingsVo.setStrangerQuestion(question);
        userSettingsVo.setGonggaoNotification(settings.getGonggaoNotification() == 1 ? true : false);
        userSettingsVo.setLikeNotification(settings.getLikeNotification() == 1 ? true : false);
        userSettingsVo.setPinglunNotification(settings.getPinglunNotification() == 1 ? true : false);
        return userSettingsVo;
    }

    /**
     * 设置陌生人问题
     * @param content
     * @return
     */
    public Boolean setQuestions(String content) {
        User user = UserThreadLocal.get();
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        Question setQuestion = new Question();
        setQuestion.setTxt(content);
        queryWrapper.eq("user_id", user.getId());
        return questionMapper.update(setQuestion, queryWrapper) > 0;

    }

    /**
     * 通知状态管理
     * @param pinglunNotification
     * @param likeNotification
     * @param gonggaoNotification
     * @return
     */
    public boolean setNotice(boolean pinglunNotification,
                             boolean likeNotification,
                             boolean gonggaoNotification) {
        User user = UserThreadLocal.get();
        Settings settings = new Settings();
        settings.setLikeNotification(likeNotification == true ? 1 : 0);
        settings.setGonggaoNotification(gonggaoNotification == true ? 1 : 0);
        settings.setPinglunNotification(pinglunNotification == true ? 1 : 0);
        QueryWrapper<Settings> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        return userSettingsMapper.update(settings, queryWrapper) > 0;
    }

    /**
     * 黑名单列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryBlackList(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
//        通过登陆者id查询出黑名单对象集合
        QueryWrapper<BlackList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        List<BlackList> blackLists = blackListMapper.selectList(queryWrapper);
//        设置分页
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
//新建集合封装黑名单对象
        List<BlackListVo> blackListVoList = new ArrayList<>();
//        遍历黑名单集合获取每个黑名单用户
        for (BlackList blackList : blackLists) {
            BlackListVo blackListVo = new BlackListVo();
//            通过黑名单用户id查询黑名单用户详细信息，将黑名单用户详细信息封装到用户对象中
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", blackList.getBlackUserId());
            UserInfo userInfo = userInfoMapper.selectOne(wrapper);
            blackListVo.setId(userInfo.getUserId());
            blackListVo.setAge(userInfo.getAge());
            blackListVo.setGender(userInfo.getSex().getValue() == 1 ? "man" : "women");
            blackListVo.setAvatar(userInfo.getLogo());
            blackListVo.setNickname(userInfo.getNickName());
            blackListVoList.add(blackListVo);
        }
        pageResult.setItems(blackListVoList);
        return pageResult;
    }

    /**
     * 黑名单取消
     * @param userId
     * @return
     */
    public boolean deleteBlack(Long userId) {
//        通过userid和黑名单用户id取消黑名单
        User user = UserThreadLocal.get();
        QueryWrapper<BlackList> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", user.getId()).eq("black_user_id",userId);
        int result = blackListMapper.delete(wrapper);
        if (result!=0){
            return true;
        }
        return false;
    }

    public Boolean fansLike(Long userId) {
        return tanHuaService.likeUser(userId);
    }

    /**
     * 用户取消喜欢
     * @param likeUserId
     */
    public void disLike(Long likeUserId) {
        User user = UserThreadLocal.get();
        Boolean mutualLike = userLikeApi.isMutualLike(user.getId(), likeUserId);
        userLikeApi.notLikeUser(user.getId(),likeUserId);
        if (mutualLike){
             imService.remove(likeUserId);
        }

    }
}